<template>
  <div>
    <div class="filter">
      <button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: currentTab === tab.value }"
        @click="changeTab(tab.value)"
      >
        {{ tab.label }}
      </button>
    </div>

    <!-- Survey Cards -->
    <div
      v-for="survey in paginatedSurveys"
      :key="survey.survey_id"
      class="exam-card"
      @click="goToSurveyDetail(survey)"
    >
      <!-- Completed Watermark -->
      <div v-if="survey.is_finished" class="completed-watermark">
        <img src="@/assets/picture/isSubmit.png" alt="已完成" />
      </div>

      <div class="exam-content">
        <div class="exam-header">
          <span class="badge" :class="statusBadgeClass(survey.status)">
            {{ statusLabel(survey.status) }}
          </span>
          <p style="font-weight:bold;">{{ survey.paper_title }}</p>
        </div>
        <div style="display:flex; font-size: 12px; color: gray;">
          <p style="margin-right: 10px;">截止时间: {{ survey.end_time }}</p>
          <p style="margin-right: 10px;">题目数量: {{ survey.qs_cnt }}</p>
        </div>
      </div>
    </div>

    <PagiNation :currentPage="currentPage" :totalPages="totalPages" @page-change="handlePageChange" />
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import PagiNation from '@/components/PagiNation.vue';
import { getStuSurveyList } from '@/services/api';

export default {
  name: 'StudentSurveyView',
  components: { PagiNation },
  props: {
    classId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
    const router = useRouter();
    const userId = Number(localStorage.getItem('id'));
    const currentTab = ref(null); // null = 全部
    const currentPage = ref(1);
    const itemsPerPage = 8;

    const tabs = ref([
      { label: '全部考试', value: null },
      { label: '进行中', value: 1 },
      { label: '已截止', value: 2 }
    ]);

    const surveys = ref([]);

    const loadSurveys = async () => {
      try {
        const response = await getStuSurveyList(userId, props.classId, currentTab.value);
        if (response.data.status === 1) {
          const now = new Date();
          surveys.value = response.data.data.map(item => {
            const end = new Date(item.end_time);
            const status = end > now ? 1 : 2; // 人工计算状态
            return { ...item, status };
          });
        }
      } catch (e) {
        console.error('加载问卷失败:', e);
      }
    };

    const goToSurveyDetail = (survey) => {
      router.push({
        name: 'StuServayDetail',
        params: { paperId: survey.paper_id },
        query: { surveyId: survey.survey_id, isFinished: survey.is_finished,SSId:survey.survey_stu_id }
      });
    };

    const filteredSurveys = computed(() => {
      if (currentTab.value === null) {
        return surveys.value;
      } else {
        return surveys.value.filter(survey => survey.status === currentTab.value);
      }
    });

    const paginatedSurveys = computed(() => {
      const start = (currentPage.value - 1) * itemsPerPage;
      const end = start + itemsPerPage;
      return filteredSurveys.value.slice(start, end);
    });

    const totalPages = computed(() => {
      return Math.ceil(filteredSurveys.value.length / itemsPerPage);
    });

    const changeTab = (tabValue) => {
      currentTab.value = tabValue;
      currentPage.value = 1;
      loadSurveys();
    };

    const handlePageChange = (newPage) => {
      currentPage.value = newPage;
    };

    const statusLabel = (status) => {
      switch (status) {
        case 1: return '进行中';
        case 2: return '已截止';
        default: return '未知';
      }
    };

    const statusBadgeClass = (status) => {
      switch (status) {
        case 1: return 'badge-in-progress';
        case 2: return 'badge-closed';
        default: return 'badge-unknown';
      }
    };

    onMounted(() => {
      loadSurveys();
    });

    return {
      currentTab,
      tabs,
      currentPage,
      totalPages,
      paginatedSurveys,
      changeTab,
      handlePageChange,
      goToSurveyDetail,
      statusLabel,
      statusBadgeClass
    };
  },
};
</script>

<style scoped>
.filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.filter button {
  background: none;
  border: none;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  color: #333;
}
.filter button.active {
  color: #244382;
  border-bottom: 2px solid #244382;
  font-weight: bold;
}
.exam-card {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 15px;
  display: flex;
  transition: 0.3s;
  position: relative;
}
.exam-card:hover {
  transform: translateY(-5px);
  background-color: #f0f0f0;
}
.exam-content {
  flex: 1;
}
.exam-header {
  display: flex;
  align-items: center;
  gap: 15px;
}
.badge {
  padding: 5px 10px;
  border-radius: 12px;
  font-size: 14px;
}
.badge-in-progress {
  background-color: #d6ffdb;
  color: #3b995c;
}
.badge-closed {
  background-color: #f0f0f0cc;
  color: #666;
}
/* Completed Watermark */
.completed-watermark {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
}
.completed-watermark img {
  width: 50px;
  height: auto;
}
</style>
